import React from 'react';
import { X, Plus, User, Globe, Home } from 'lucide-react';
import { useApp } from '../contexts/AppContext';
import clsx from 'clsx';

interface TabBarProps {
  onNewTab: () => void;
}

export function TabBar({ onNewTab }: TabBarProps) {
  const { state, dispatch } = useApp();

  const handleCloseTab = (tabId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    dispatch({ type: 'CLOSE_TAB', payload: tabId });
  };

  const handleSwitchTab = (tabId: string) => {
    dispatch({ type: 'SWITCH_TAB', payload: tabId });
  };

  // 获取标签页的favicon或默认图标
  const getTabIcon = (tab: any) => {
    if (tab.favicon) {
      return <img src={tab.favicon} alt="" className="w-4 h-4 rounded" />;
    }
    
    // 根据URL判断图标
    if (tab.url.includes('douyin')) return <User size={14} className="text-pink-500" />;
    if (tab.url.includes('kuaishou')) return <User size={14} className="text-orange-500" />;
    if (tab.url.includes('xiaohongshu')) return <User size={14} className="text-red-500" />;
    if (tab.url.includes('weibo')) return <User size={14} className="text-yellow-500" />;
    if (tab.url.includes('bilibili')) return <User size={14} className="text-blue-500" />;
    
    return <Globe size={14} className="text-gray-400" />;
  };

  // 获取标签页的显示标题
  const getTabTitle = (tab: any) => {
    if (tab.title && tab.title !== '新建标签页') {
      return tab.title;
    }
    
    // 根据URL生成标题
    try {
      const url = new URL(tab.url);
      return url.hostname.replace('www.', '');
    } catch {
      return '新建标签页';
    }
  };

  return (
    <div className="flex items-center bg-[#f5f5f5] border-b border-[#dadce0] pl-3 pr-2 pt-1 pb-0">
      {/* 新建标签页按钮 - Chrome精确风格 */}
      <div className="flex items-center h-9 mr-2">
        <button
          onClick={onNewTab}
          className="flex items-center justify-center w-8 h-8 text-gray-600 hover:bg-gray-300 rounded-full transition-colors duration-150"
          title="新建标签页"
        >
          <Plus size={18} />
        </button>
      </div>

      {/* 标签页容器 - Chrome精确布局 */}
      <div className="flex-1 flex items-end overflow-x-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-transparent">
        {state.tabs.length === 0 ? (
          // 空状态
          <div className="flex items-center justify-center w-full py-8">
            <div className="text-center text-gray-500">
              <Home size={32} className="mx-auto mb-2 text-gray-300" />
              <p className="text-sm">点击 + 按钮创建第一个标签页</p>
            </div>
          </div>
        ) : (
          state.tabs.map((tab, index) => {
            const account = state.accounts.find(acc => acc.id === tab.accountId);
            const isFirstTab = index === 0;
            const isLastTab = index === state.tabs.length - 1;
            const isSingleTab = state.tabs.length === 1;
            
            return (
              <div
                key={tab.id}
                onClick={() => handleSwitchTab(tab.id)}
                className={clsx(
                  'group relative flex items-center min-w-[200px] max-w-[280px] h-9 px-4 cursor-pointer',
                  'border border-transparent transition-all duration-150',
                  
                  // Chrome标签栏精确设计
                  tab.isActive
                    ? [
                        // 激活标签：白色背景，加大圆角
                        'bg-white border-[#dadce0]',
                        'z-10',
                        // 无缝连接处理 - 加大圆角
                        isFirstTab ? 'rounded-tl-xl ml-0' : 'ml-[-1px]',
                        isLastTab ? 'rounded-tr-xl mr-0' : 'mr-[-1px]',
                        isSingleTab ? 'rounded-t-xl mx-0' : '',
                        // Chrome阴影效果
                        'shadow-[0_1px_3px_rgba(0,0,0,0.15)]',
                        // 底部边框处理
                        'border-b-white mb-[-1px]',
                        // 顶部留白
                        'mt-1'
                      ]
                    : [
                        // 非激活标签：浅灰色背景
                        'bg-[#f1f3f4] hover:bg-[#e8eaed]',
                        'border-[#dadce0] border-b-[#dadce0]',
                        'hover:border-[#c4c7d0]',
                        // 无缝连接处理 - 加大圆角
                        isFirstTab ? 'rounded-tl-xl ml-0' : 'ml-[-1px]',
                        isLastTab ? 'rounded-tr-xl mr-0' : 'mr-[-1px]',
                        isSingleTab ? 'rounded-t-xl mx-0' : '',
                        // Chrome内阴影效果
                        'shadow-[inset_0_-1px_0_0_#dadce0]',
                        // 悬停效果
                        'hover:shadow-[inset_0_-1px_0_0_#c4c7d0]',
                        // 顶部留白
                        'mt-1'
                      ]
                )}
                style={{
                  marginTop: tab.isActive ? '2px' : '4px'
                }}
              >
                {/* Chrome标签页装饰线 */}
                {tab.isActive && (
                  <>
                    {/* 顶部高亮线 - 加大圆角 */}
                    <div className="absolute top-0 left-0 right-0 h-[3px] bg-blue-500 rounded-t-xl"></div>
                    {/* 左侧装饰线 */}
                    <div className="absolute left-0 top-[3px] bottom-0 w-[1px] bg-gradient-to-b from-blue-400 to-blue-200"></div>
                    {/* 右侧装饰线 */}
                    <div className="absolute right-0 top-[3px] bottom-0 w-[1px] bg-gradient-to-b from-blue-400 to-blue-200"></div>
                  </>
                )}
                
                {/* 标签页内容 - Chrome精确布局 */}
                <div className="flex items-center flex-1 min-w-0 space-x-3">
                  {/* 网站图标 - Chrome布局 */}
                  <div className="flex items-center justify-center w-4 h-4">
                    {getTabIcon(tab)}
                  </div>
                  
                  {/* 账号标识徽章 */}
                  {account && (
                    <div 
                      className="flex items-center justify-center w-3 h-3 bg-gradient-to-br from-blue-400 to-blue-600 rounded-full"
                      title={`${account.username} (${account.platform})`}
                    >
                      <User size={8} className="text-white" />
                    </div>
                  )}
                  
                  {/* 标签页标题 - Chrome字体和间距 */}
                  <span className={clsx(
                    'flex-1 truncate text-[13px] font-normal transition-all duration-150',
                    tab.isActive ? 'text-[#1f1f1f]' : 'text-[#5f6368]'
                  )}>
                    {getTabTitle(tab)}
                  </span>
                  
                  {/* 平台标识（未绑定账号时） */}
                  {tab.platform && !account && (
                    <span 
                      className="px-1.5 py-0.5 text-[10px] font-medium text-gray-600 bg-gray-200 rounded"
                      title={tab.platform}
                    >
                      {tab.platform.substring(0, 2)}
                    </span>
                  )}
                  
                  {/* 关闭按钮 - Chrome精确设计 */}
                  <button
                    onClick={(e) => handleCloseTab(tab.id, e)}
                    className={clsx(
                      'flex items-center justify-center w-6 h-6 rounded-full transition-all duration-150',
                      'hover:bg-gray-300',
                      // Chrome关闭按钮显示逻辑
                      tab.isActive ? 'opacity-100' : 'group-hover:opacity-100 opacity-0',
                      'focus:outline-none focus:ring-1 focus:ring-gray-400'
                    )}
                    title="关闭标签页"
                  >
                    <X size={12} className="text-gray-600 hover:text-gray-800" />
                  </button>
                </div>
                
                {/* 加载状态指示器 - Chrome风格 */}
                {tab.isLoading && (
                  <div className="absolute bottom-0 left-0 right-0 h-[3px] bg-gradient-to-r from-blue-400 to-blue-600 rounded-b-xl">
                    <div className="h-full w-1/2 bg-white animate-pulse rounded-full"></div>
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>
      
      {/* 右侧空白区域（用于Chrome布局对齐） */}
      <div className="w-2"></div>
    </div>
  );
}